package com.zhiyun.hxzy.service;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.zhiyun.hxzy.dao.ClassesDao;
import com.zhiyun.hxzy.dao.TeacherDao;
import com.zhiyun.hxzy.domain.Classes;
import com.zhiyun.hxzy.domain.School;
import com.zhiyun.hxzy.domain.queryvo.Result;
import com.zhiyun.hxzy.domain.Teacher;
import com.zhiyun.hxzy.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.*;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Transactional
@Service
public class TeacherService {
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private ClassesDao classesDao;
    @Autowired
    private MailUtil mailUtil;
    @Autowired
    private SMSUtil smsUtil;
    @Autowired
    private SMSUtil2 smsUtil2;
    @Autowired
    private CodeUtil codeUtil;
    @Autowired
    private RedisTemplate<Object, Object> template;
    @Autowired
    private UploadUtil uploadUtil;

    public Page<Teacher> findAll(int pageNum, int pageSize, Long schoolId) {
        //根据schoolId拼一个条件
        Specification specification = null;
        if (schoolId != null) {
            specification = new Specification() {
                @Override
                public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                    Path schoolId2 = root.get("school");
                    List<Predicate> list = new ArrayList<>();
                    list.add(criteriaBuilder.equal(schoolId2,schoolId));
                    Predicate p4 = criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
                    return p4;
                }
            };
        }
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);
        return teacherDao.findAll(specification,pageRequest);
    }

    public Teacher findById(Long id) {
        return teacherDao.findById(id).get();
    }

    public void modify(Teacher teacher) {
        Teacher one = teacherDao.getOne(teacher.getId());
        teacher.setPassword(one.getPassword());
        teacherDao.save(teacher);
    }

    public void del(Long[] id) {
        for (Long i : id) {
            teacherDao.deleteById(i);
        }
    }

    public void addClasses(Long teacherId, Long[] classesId) {
        Teacher teacher = findById(teacherId);
        List<Classes> classesList = classesDao.findClassesByNotHaveTeacher(teacherId,teacher.getSchool().getId());
        for (int i = 0; i < classesId.length; i++) {
            Classes classes = classesDao.findById(classesId[i]).get();
            classesList = teacher.getClassesList();
            classesList.add(classes);
        }
        teacher.setClassesList(classesList);
        teacherDao.save(teacher);
    }

    public void add(Teacher teacher) throws Exception {
        String s = UUID.randomUUID().toString();
        String s1 = s.substring(0, 8);
//        mailUtil.sendMail(teacher.getEmail(), "您的初始密码为" + s1, "注册邮件");
        SendSmsResponse sendSmsResponse = smsUtil2.sendPassword(teacher.getPhone(), teacher.getName(), s1);
        System.out.println(sendSmsResponse.getCode());
        String encodeByMd5 = Md5Util.encodeByMd5(s1);
        teacher.setPassword(encodeByMd5);
        teacherDao.save(teacher);
    }

    //老师登录 通过手机号和密码查询老师
    public Teacher findByPhoneAndPassword(String phoneNum, String password) {
        String password1 = null;
        try {
            password1 = Md5Util.encodeByMd5(password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Teacher teacher = teacherDao.findByPhoneAndPassword(phoneNum, password1);
        return teacher;
    }

    //登录 给手机发送验证码
    public Result LoginSendPhoneCode(String phoneNum) {
        Teacher teacher = teacherDao.findByPhone(phoneNum);
        if (teacher != null) {
            try {
                String code = codeUtil.getCode();
                smsUtil2.sendCheckCode(phoneNum, code);
                template.opsForValue().set("login" + phoneNum, code);//key:手机号,value:验证码
                template.expire(phoneNum, 60, TimeUnit.SECONDS);//设置60S过期
            } catch (Exception e) {
                e.printStackTrace();
            }
            return new Result("已发送", true);
        } else {
            return new Result("该手机未注册", false);
        }
    }

    //验证码登录
    public Result loginVerifyCode(String phoneNum, String code) {
        Teacher teacher = teacherDao.findByPhone(phoneNum);
        if (teacher == null) {
            return new Result("该手机未注册", false);
        } else {
            String redisCode = (String) template.opsForValue().get("login" + phoneNum);
            if (code.contains(redisCode)) {
                return new Result("登陆成功", true);
            } else {
                return new Result("验证码错误", false);
            }
        }
    }

    //通过手机号查询老师
    public Teacher findByPhoneNum(String phoneNum) {
        Teacher teacher = teacherDao.findByPhone(phoneNum);
        return teacher;
    }

    //老师重置密码
    public void resetPassword(String password, String phoneNum) {
        if (phoneNum != null && password != null) {
            String passwordNew = null;
            try {
                passwordNew = Md5Util.encodeByMd5(password);
            } catch (Exception e) {
                e.printStackTrace();
            }
            teacherDao.resetPassword(passwordNew, phoneNum);
        }
    }

    public Result uploadUimg(MultipartFile file) {
        String path = uploadUtil.upload(file);
        return new Result(path,true);
    }
}
